package com.zbkj.service.dividend.service;

import com.zbkj.common.model.user.User;
import com.zbkj.service.dividend.model.DividendPoolConfig;
import com.zbkj.service.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;

@Service
public class DividendPoolChangeService {

    @Autowired
    private UserService userService;

    @Autowired
    private DividendPoolConfigService dividendPoolConfigService;

    @Value("${dividendPool.enableConfig}")
    private boolean enableDividendPool;


    private static final Logger log = LoggerFactory.getLogger(DividendPoolChangeService.class);

    /**
     * 用户进入或变更分红池
     *
     * @param uid 用户ID
     */
    public void updateUserDividendPool(int uid) {
        if (enableDividendPool) {
            log.info("分红池变更已开启");
        } else {
            log.info("分红池变更未开启");
            return;
        }

        try {
            // 1. 获取分红配置列表（带缓存）
            List<DividendPoolConfig> configList = dividendPoolConfigService.getAllActiveConfigs();
            if (CollectionUtils.isEmpty(configList)) {
                log.warn("分红配置列表为空，用户ID: {}", uid);
                return;
            }

            // 2. 获取用户信息
            User userInfo = userService.getById(uid);
            if (userInfo == null) {
                log.error("用户不存在，用户ID: {}", uid);
                return;
            }

            // 3. 获取用户当前余额
            BigDecimal nowMoney = userInfo.getNowMoney();
            if (nowMoney == null) {
                log.warn("用户余额为空，用户ID: {}", uid);
                return;
            }

            // 4. 获取用户当前分红配置
            Integer currentDividendId = userInfo.getDividendPoolId();
            DividendPoolConfig currentConfig = dividendPoolConfigService.getCurrentDividendConfig(currentDividendId);

            // 5. 根据余额确定合适的分红配置
            DividendPoolConfig suitableConfig = findSuitableConfig(configList, nowMoney);

            // 6. 判断并执行分红池变更
            processDividendPoolChange(uid, userInfo, currentConfig, suitableConfig, nowMoney);

        } catch (Exception e) {
            log.error("用户分红池变更异常，用户ID: {}", uid, e);
        }
    }



    /**
     * 根据余额找到合适的分红配置
     * 核心逻辑：选择用户余额能满足的最高档位分红池
     */
    private DividendPoolConfig findSuitableConfig(List<DividendPoolConfig> configList, BigDecimal balance) {
        if (CollectionUtils.isEmpty(configList) || balance == null) {
            return null;
        }

        // 使用Stream API找到用户余额能满足的最高档位分红池
        return configList.stream()
                .filter(config -> Boolean.TRUE.equals(config.getIsActive())) // 只考虑启用的配置
                .filter(config -> isBalanceMeetRequirement(balance, config)) // 满足余额要求
                .max(Comparator.comparing(DividendPoolConfig::getLevel))     // 选择最高档位
                .orElse(null);                                               // 没有满足条件的返回null
    }

    /**
     * 检查余额是否满足配置要求
     * 核心逻辑：余额必须 >= 分红档位要求
     */
    private boolean isBalanceMeetRequirement(BigDecimal balance, DividendPoolConfig config) {
        if (config == null || balance == null) {
            return false;
        }

        // 检查配置是否启用
        if (!Boolean.TRUE.equals(config.getIsActive())) {
            return false;
        }

        // 核心逻辑：余额必须大于等于分红档位要求
        return balance.compareTo(BigDecimal.valueOf(config.getLevel())) >= 0;
    }

    /**
     * 处理分红池变更逻辑
     */
    private void processDividendPoolChange(int uid, User userInfo, DividendPoolConfig currentConfig,
                                           DividendPoolConfig suitableConfig, BigDecimal nowMoney) {
        // 情况1：用户没有分红池，但满足加入条件
        if (currentConfig == null && suitableConfig != null) {
            joinDividendPool(uid, userInfo, suitableConfig, nowMoney);
            return;
        }

        // 情况2：用户已有分红池，但余额不足需要退出
        if (currentConfig != null && suitableConfig == null) {
            exitDividendPool(uid, userInfo, currentConfig, nowMoney);
            return;
        }

        // 情况3：用户需要变更分红池
        if (currentConfig != null && !currentConfig.getId().equals(suitableConfig.getId())) {
            changeDividendPool(uid, userInfo, currentConfig, suitableConfig, nowMoney);
        }

        // 情况4：无变化
    }

    /**
     * 加入分红池
     */
    private void joinDividendPool(int uid, User userInfo, DividendPoolConfig suitableConfig, BigDecimal nowMoney) {
        try {
            // 更新用户分红ID
            userInfo.setDividendPoolId(suitableConfig.getId());
            userInfo.setDividendPoolTag(suitableConfig.getTagName());
            boolean updateSuccess = userService.updateById(userInfo);

            if (updateSuccess) {
                log.info("用户加入分红池成功，用户ID: {}, 分红池ID: {}, 档位: {}元, 余额: {}",
                        uid, suitableConfig.getId(), suitableConfig.getLevel(), nowMoney);
            }
        } catch (Exception e) {
            log.error("用户加入分红池失败，用户ID: {}, 分红池ID: {}", uid, suitableConfig.getId(), e);
        }
    }

    /**
     * 退出分红池
     */
    private int exitDividendPool(int uid, User userInfo, DividendPoolConfig currentConfig, BigDecimal nowMoney) {
        try {
            // 更新用户分红ID为0（退出）
            userInfo.setDividendPoolId(0);
            userInfo.setDividendPoolTag("普通用户");
            boolean updateSuccess = userService.updateById(userInfo);

            if (updateSuccess) {
                log.info("用户退出分红池成功，用户ID: {}, 原分红池ID: {}, 原档位: {}元, 余额: {}",
                        uid, currentConfig.getId(), currentConfig.getLevel(), nowMoney);
                return -2;
            }
        } catch (Exception e) {
            log.error("用户退出分红池失败，用户ID: {}, 原分红池ID: {}", uid, currentConfig.getId(), e);
        }
        return 0;
    }

    /**
     * 变更分红池
     */
    private void changeDividendPool(int uid, User userInfo, DividendPoolConfig currentConfig,
                                    DividendPoolConfig suitableConfig, BigDecimal nowMoney) {
        try {
            // 判断是升级还是降级
            boolean isUpgrade = suitableConfig.getLevel() > currentConfig.getLevel();

            // 更新用户分红ID
            userInfo.setDividendPoolId(suitableConfig.getId());
            userInfo.setDividendPoolTag(suitableConfig.getTagName());
            boolean updateSuccess = userService.updateById(userInfo);

            if (updateSuccess) {
                log.info("用户变更分红池成功，用户ID: {}, 原档位: {}元->新档位: {}元, 余额: {}",
                        uid, currentConfig.getLevel(), suitableConfig.getLevel(), nowMoney);

            }
        } catch (Exception e) {
            log.error("用户变更分红池失败，用户ID: {}, 原分红池ID: {}, 新分红池ID: {}",
                    uid, currentConfig.getId(), suitableConfig.getId(), e);
        }
    }

}